"use client";

import { articleApi } from '@/constants';
import { get, post, put, patch, del } from '@/util/api';

// 文章基本信息接口
export interface ArticleBase {
  title: string;
  content: string;
  categoryId: number;
  tagIds: number[];
  summary?: string;
  coverImage?: string;
  isTop?: number;
  status?: number; // -1待审核，0审核失败，1审核成功
}

// 文章响应接口
export interface Article extends ArticleBase {
  id: number;
  userId: number;
  username?: string;
  viewCount: number;
  likeCount: number;
  commentCount: number;
  createdAt: string;
  updatedAt: string;
  isActive?: number;
  category?: {
    id: number;
    name: string;
  };
  tags?: Array<{
    id: number;
    name: string;
  }>;
}

// 文章列表响应接口
export interface ArticleListResponse {
  data: Article[];
  total: number;
  page: number;
  pageSize: number;
}

// 文章统计数据接口
export interface ArticleStats {
  totalCount: number;
  pendingCount: number;
  publishedCount: number;
  rejectedCount: number;
  monthlyPublish: Array<{
    month: string;
    count: number;
  }>;
  categoryDistribution: Array<{
    categoryId: number;
    categoryName: string;
    count: number;
  }>;
}

/**
 * 文章管理服务类
 * 封装所有文章相关的API调用
 */
class ArticleService {
  /**
   * 获取文章列表
   * @param params 查询参数
   * @returns Promise<ArticleListResponse>
   */
  async getArticleList(params?: {
    page?: number;
    pageSize?: number;
    keyword?: string;
    categoryId?: number;
    tagId?: number;
    status?: number;
    userId?: number;
    startDate?: string;
    endDate?: string;
    isActive?: number
  }) {
    try {
      const response = await get(articleApi.LIST, {params});
      return response;
    } catch (error) {
      console.error('获取文章列表失败:', error);
      throw error;
    }
  }

  /**
   * 获取文章详情
   * @param id 文章ID
   * @returns Promise<Article>
   */
  async getArticleDetail(id: number) {
    try {
      const response = await get(articleApi.DETAIL(id));
      return response.data || response;
    } catch (error) {
      console.error(`获取文章详情失败 (ID: ${id}):`, error);
      throw error;
    }
  }

  /**
   * 创建文章
   * @param articleData 文章数据
   * @returns Promise<Article>
   */
  async createArticle(articleData: Partial<ArticleBase>) {
    try {
      const response = await post(articleApi.CREATE, articleData);
      return response.data || response;
    } catch (error) {
      console.error('创建文章失败:', error);
      throw error;
    }
  }

  /**
   * 更新文章
   * @param id 文章ID
   * @param articleData 文章数据
   * @returns Promise<Article>
   */
  async updateArticle(id: number, articleData: Partial<ArticleBase>) {
    try {
      const response = await put(articleApi.UPDATE(id), articleData);
      return response.data || response;
    } catch (error) {
      console.error(`更新文章失败 (ID: ${id}):`, error);
      throw error;
    }
  }

  /**
   * 更新文章状态
   * @param id 文章ID
   * @param status 状态值
   * @returns Promise<Article>
   */
  async updateArticleStatus(id: number, status: number){
    try {
      const response = await put(articleApi.UPDATE_STATUS(id), { isActive: status });
      return response.data || response;
    } catch (error) {
      console.error(`更新文章状态失败 (ID: ${id}):`, error);
      throw error;
    }
  }

  /**
   * 删除文章
   * @param id 文章ID
   */
  async deleteArticle(id: number): Promise<void> {
    try {
      await del(articleApi.DELETE(id));
    } catch (error) {
      console.error(`删除文章失败 (ID: ${id}):`, error);
      throw error;
    }
  }

  /**
   * 批量操作文章
   * @param ids 文章ID数组
   * @param action 操作类型
   * @returns Promise<any>
   */
  async batchOperateArticles(ids: number[], action: string): Promise<unknown> {
    try {
      const response = await patch(articleApi.BATCH_OPERATE, { ids, action });
      return response.data || response;
    } catch (error) {
      console.error('批量操作文章失败:', error);
      throw error;
    }
  }

  /**
   * 上传文章封面
   * @param file 文件对象
   * @returns Promise<{ url: string }>
   */
  async uploadCover(file: File): Promise<{ url: string }> {
    try {
      const formData = new FormData();
      formData.append('file', file);
      
      const response = await post(articleApi.UPLOAD_COVER, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      
      return ( response.data  || response) as { url: string };
    } catch (error) {
      console.error('上传文章封面失败:', error);
      throw error;
    }
  }

  /**
   * 获取文章统计数据
   * @returns Promise<ArticleStats>
   */
  async getArticleStats(): Promise<ArticleStats> {
    try {
      const response = await get(articleApi.STATS);
      return (response.data || response) as ArticleStats;
    } catch (error) {
      console.error('获取文章统计数据失败:', error);
      throw error;
    }
  }
}

// 导出文章服务实例
export const articleService = new ArticleService();
export default articleService;